// 假定我们有一个可以返回 Promise 的通用 API（请忽略此 API 具体实现细节）
import { fetchItems } from '../api'

export default function (http) {
  const state = {
    items: [],
    banners: [],
    documents: []
  }

  const mutations = {
    SET_ITEMS (state, data) {
      state.items = data
    },
    SET_BANNERS (state, data) {
      state.banners = data
    },
    SET_DOCUMENTS (state, data) {
      state.documents = data
    }
  }

  const actions = {
    fetchItems ({ commit }) {
      // `store.dispatch()` 会返回 Promise，以便我们能够知道数据在何时更新
      return fetchItems().then(data => {
        commit('SET_ITEMS', data)
      })
    },
    fetchBanners ({ commit }) {
      return http.get('/v1/web/prefecture/banners_front').then(resp => {
        commit('SET_BANNERS', resp.data.data)
      }).catch((err) => {
        console.log(err)
      })
    },
    fetchDocuments ({ commit }) {
      return http.post('/v1/web/prefecture/documents/download_records', {
        beginDate: '2019-07-31',
        endDate: '2019-08-30',
        pageNumber: 1,
        pageSize: 10,
        totalPages: 0
      }).then(resp => {
        commit('SET_DOCUMENTS', resp.data.data.content)
      }).catch((err) => {
        console.log(err)
      })
    }
  }

  return {
    state,
    mutations,
    actions
  }
}
